<template>
  <div class="product-detail">
    <header class="header">
      <div class="top-nav">
        <div class="nav-container">
          <div class="logo">
            <img src="/public/logo.png" alt="宠物商城" />
          </div>
          <router-link to="/" class="nav-item">首页</router-link>
          <router-link to="/type" class="nav-item">商品分类</router-link>
          <router-link to="/carts" class="nav-item">购物车</router-link>
          <router-link to="/personal-center" class="nav-item"
            >个人中心</router-link
          >
        </div>
      </div>
      <div class="call">
        <router-link to="/service" class="call-item">
          <img src="../meall/me-img/call.png" alt="" class="call-img" />
          客服
        </router-link>
      </div>
    </header>

    <div class="main-content">
      <div v-if="product" class="product-container">
        <div class="product-images">
          <div class="thumbnail-list">
            <img
              v-for="(image, index) in product.images"
              :key="index"
              :src="image"
              :alt="`缩略图${index + 1}`"
              class="thumbnail"
              :class="{ active: image === currentImage }"
              @click="currentImage = image"
            />
          </div>
          <img :src="currentImage" :alt="product.name" class="main-image" />
        </div>
        <div class="product-info">
          <h1 class="product-title">{{ product.name }}</h1>
          <div class="product-price">¥{{ product.price.toFixed(2) }}</div>
          <div class="product-meta">
            <div class="meta-item">
              <span class="meta-label">销量:</span>
              <span class="meta-value">{{ product.sales }}+</span>
            </div>
            <div class="meta-item">
              <span class="meta-label">库存:</span>
              <span class="meta-value">{{ product.stock_quantity }}件</span>
            </div>
          </div>
          <div class="quantity-control">
            <span class="quantity-label">数量:</span>
            <button
              @click="updateQuantity(-1)"
              class="quantity-btn minus-btn"
              :disabled="quantity <= 1"
            >
              -
            </button>
            <input
              type="text"
              class="quantity-input"
              v-model.number="quantity"
              readonly
            />
            <button
              @click="updateQuantity(1)"
              class="quantity-btn plus-btn"
              :disabled="quantity >= product.stock_quantity"
            >
              +
            </button>
          </div>
          <div class="product-actions">
            <button @click="addToCart" class="add-to-cart-btn">
              加入购物车
            </button>
            <button @click="buyNow" class="buy-now-btn">立即购买</button>
            <button
              @click="toggleFavorite"
              class="favorite-btn"
              :class="{ favorited: isFavorited }"
            >
              {{ isFavorited ? "已收藏" : "收藏商品" }}
            </button>
          </div>
          <div class="product-description">
            <h3>商品描述</h3>
            <p>{{ product.description }}</p>
          </div>
        </div>
      </div>
      <div v-else class="loading">
        <p>加载中...</p>
      </div>
    </div>
  </div>
</template>

<script>
import { mapMutations } from "vuex";

export default {
  name: "ProductDetail",
  data() {
    return {
      product: null,
      quantity: 1,
      currentImage: "",
      favorites: JSON.parse(localStorage.getItem("favorites")) || [],
      isFavorited: false,
    };
  },
  created() {
    this.fetchProductDetail();
  },
  methods: {
    ...mapMutations(["addToCart"]),
    async fetchProductDetail() {
      try {
        const productId = this.$route.params.id;
        const response = await fetch("/public/product.json");
        const data = await response.json();

        // 确保正确匹配商品ID
        const product = data.cart.items.find(
          (item) => item.product_id.toString() === productId.toString()
        );

        if (product) {
          this.product = {
            ...product,
            // 处理可能不存在的images数组
            images: product.images || [product.image_url],
          };
          this.currentImage = this.product.images[0];

          // 检查是否已收藏
          this.checkIfFavorited();
        } else {
          console.error("未找到商品");
          this.$router.push("/not-found");
        }
      } catch (error) {
        console.error("加载商品详情失败:", error);
      }
    },
    checkIfFavorited() {
      this.isFavorited = this.favorites.some(
        (item) => item.id === this.product.product_id
      );
    },
    toggleFavorite() {
      if (this.isFavorited) {
        // 取消收藏
        this.favorites = this.favorites.filter(
          (item) => item.id !== this.product.product_id
        );
        this.isFavorited = false;
        alert("已取消收藏");
      } else {
        // 添加收藏
        const favoriteItem = {
          id: this.product.product_id,
          name: this.product.name,
          price: this.product.price,
          image: this.product.images[0],
          specs: this.product.description,
          status: "collectProducts",
        };
        this.favorites.push(favoriteItem);
        this.isFavorited = true;
        alert("商品已收藏");
      }

      // 保存到localStorage
      localStorage.setItem("favorites", JSON.stringify(this.favorites));
    },
    updateQuantity(change) {
      const newQuantity = this.quantity + change;
      if (newQuantity >= 1 && newQuantity <= this.product.stock_quantity) {
        this.quantity = newQuantity;
      }
    },
    addToCart() {
      this.$store.commit("addToCart", {
        ...this.product,
        quantity: this.quantity,
      });
      alert("商品已添加到购物车");
    },
    buyNow() {
      this.addToCart();
      this.$router.push("/carts");
    },
  },
};
</script>

<style scoped>
.product-detail {
  background-color: #f9f7e8;
  min-height: 100vh;
}

.main-content {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.product-container {
  display: flex;
  background-color: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.product-images {
  flex: 1;
  padding-right: 30px;
}

.main-image {
  width: 100%;
  max-width: 500px;
  height: auto;
  border-radius: 8px;
  margin-bottom: 20px;
}

.thumbnail-list {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.thumbnail {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
  border: 2px solid transparent;
  transition: all 0.3s;
}

.thumbnail.active {
  border: 2px solid #f56c6c;
}

.product-info {
  flex: 1;
}

.product-title {
  font-size: 24px;
  margin-bottom: 15px;
  color: #333;
}

.product-price {
  font-size: 28px;
  color: #f56c6c;
  font-weight: bold;
  margin-bottom: 20px;
}

.product-meta {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.meta-item {
  display: flex;
  align-items: center;
}

.meta-label {
  color: #666;
  margin-right: 5px;
}

.meta-value {
  color: #333;
  font-weight: 500;
}

.quantity-control {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
}

.quantity-label {
  margin-right: 15px;
  color: #666;
}

.quantity-btn {
  width: 30px;
  height: 30px;
  background-color: #f4efd2;
  border: 1px solid #ddd;
  font-size: 16px;
  cursor: pointer;
}

.quantity-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.quantity-input {
  width: 50px;
  height: 30px;
  text-align: center;
  margin: 0 5px;
  border: 1px solid #ddd;
}

.product-actions {
  display: flex;
  gap: 15px;
  margin-bottom: 30px;
  flex-wrap: wrap;
}

.add-to-cart-btn,
.buy-now-btn,
.favorite-btn {
  padding: 12px 30px;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.add-to-cart-btn {
  background-color: #d9c596;
  color: #333;
}

.buy-now-btn {
  background-color: #f56c6c;
  color: white;
}

.favorite-btn {
  background-color: #f4efd2;
  color: #333;
}

.favorite-btn.favorited {
  background-color: #f56c6c;
  color: white;
}

.add-to-cart-btn:hover {
  background-color: #f4efd2;
}

.buy-now-btn:hover {
  background-color: #e65a5a;
}

.favorite-btn:hover {
  background-color: #e6e0c2;
}

.favorite-btn.favorited:hover {
  background-color: #e65a5a;
}

.product-description {
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.product-description h3 {
  font-size: 18px;
  margin-bottom: 15px;
  color: #333;
}

.product-description p {
  color: #666;
  line-height: 1.6;
}

.loading {
  text-align: center;
  padding: 50px;
  font-size: 18px;
  color: #666;
}

/* 复用头部样式 */
.header {
  margin-bottom: 20px;
}

.top-nav {
  width: 100%;
  background-color: #f4efd2;
  color: black;
  padding: 15px 0;
  position: sticky;
  top: 0;
  z-index: 100;
  box-shadow: #bdbbb7 0px 0px 5px;
}

.nav-container {
  width: 90%;
  height: 40px;
  margin: 0 auto;
  display: flex;
  align-items: center;
}

.logo {
  margin-right: 40px;
  height: 40px;
}

img {
  height: 100%;
}

.nav-item {
  width: 60%;
  height: 40px;
  text-align: center;
  padding: 8px 40px;
  margin-right: 15px;
  cursor: pointer;
  font-size: 16px;
  border-radius: 18px;
  transition: all 0.3s;
}

.nav-item:hover {
  background-color: rgba(0, 0, 0, 0.2);
}

.call {
  background-color: #f9f7e8;
  height: 30px;
  padding: 8px;
  min-width: 1200px;
}

a {
  text-decoration: none;
  color: black;
}

.call-item {
  position: absolute;
  right: 40px;
}

.call-img {
  height: 18px;
}
</style>
